#!/usr/bin/perl -w

if(! open CONF_PRE, "dolphin.conf.ini.pre") {
	die "failed to open dolphin.conf.ini.pre";
}
if( ! open SOURCE, ">conf_pre.h") {
	die "failed to open conf_pre.h";
}
if ( ! open OUTPUT_CONF, ">dolphin.conf") {
	die "failed to open dolphin.conf";
}

#write to conf_pre.c file 
print SOURCE "static void autogen_ini_parse(const char *ini_conf);\n\n\n".
			  "static void autogen_ini_parse(const char *ini_conf)\n".
			  "{\n".
			  "\tdictionary *dic = NULL;\n\n".
			  "\tif(!ini_conf) {\n".
			  "\tdebug_log(3, \"ini_conf is %"."p\\n\", ini_conf);\n".
			  "\treturn;\n".
			  "\t}\n".
			  "\tif((dic = iniparser_load(ini_conf)) == NULL) {\n".
	          "\terror_log(errno, \"faild to load %"."s\\n\", ini_conf);\n".
		      "\treturn;\n".
	          "\t}\n\n";
			  
while(defined($line = <CONF_PRE>)) {
		#print "$line";
	@fields = split /:/, $line;
	$key = shift @fields;
	if(! defined($key)) {
		next;
	}
	chomp($key);
    $key =~ s/^ +//;   # Ltrim   
    $key =~ s/ +$//;  # Rtrim   
	
	$value = shift @fields;
	if(! defined($value))  {
		next;
	}
	chomp($value);
    $value =~ s/^ +//;   # Ltrim   
    $value =~ s/ +$//;  # Rtrim   
	  
		if($key eq 'section') {
			$section = $value;
		}
		elsif($key eq 'name') {
			$name = $value;
		}
		elsif($key eq 'type') {
			$type = $value;
		}
		elsif($key eq 'default') {
			$default = $value;
			$location = sprintf "conf->$section.$name";
			$func = sprintf "\t%s\_parse(&%s, \U$section\_$name\E, dic);\n", $type, $location;
			$one = sprintf "[$section]\n$name = \"$default\"\n\n";
			print OUTPUT_CONF $one;
			print SOURCE "$func";
		}
		else {
			print "unknown $key\n";
		}
}
print SOURCE "}\n";
